<template>
  <uni-drawer 
    ref="drawerRef" 
    mode="left" 
    :width="width" 
    :mask-click="maskClick" 
    @change="handleChange"
  >
    <view class="drawer-content">
      <scroll-view 
        class="scroll-view-box" 
        :style="{ top: props.navHeight + 'px' }"
        scroll-y="true"
        refresher-enabled="true"
        refresher-threshold="80"
        refresher-default-style="black"
        refresher-background="#f8f9fa"
        :refresher-triggered="isRefreshing"
        @refresherrefresh="handleRefresh"
        @scrolltolower="handleLoadMore"
        lower-threshold="50"
        scroll-with-animation="true"
      >
        <!-- 抽屉头部 -->
        <view class="drawer-header">
          <text class="header-text">选择你的协同仓</text>
        </view>
        
        <!-- 添加协同仓按钮 -->
        <!-- <view class="add-warehouse-section" v-if="showAddWarehouse">
          <view class="input-wrapper">
            <input  
              type="text" 
              class="warehouse-input" 
              placeholder="请输入协同仓代码或名称"
              v-model="warehouseCode"
            >
            <view class="input-icon">🔍</view>
          </view>
          <button class="add-warehouse-btn" @tap="addWarehouse">
            <text class="add-icon">+</text>
            <text class="add-text">添加协同仓</text>
          </button>
        
        </view> -->
        
        <!-- 仓库列表 -->
        <view class="warehouse-list">
          
          <!-- 刷新提示 -->
          <view v-if="isRefreshing" class="refresh-tip">
            <view class="refresh-icon">🔄</view>
            <text class="refresh-text">正在刷新数据...</text>
          </view>
          <!-- 空状态 -->
          <view v-if="warehouseList.length === 0" class="empty-state">
            <view class="empty-icon">📦</view>
            <text class="empty-title">暂无协同仓</text>
            <text class="empty-desc">您还没有可用的协同仓库，点击上方按钮添加</text>
          </view>
          
          <!-- 仓库列表 -->
          <view v-else>
            <view class="warehouse-item" 
              v-for="item in warehouseList" 
              :key="item['rowid']" 
              :class="{ 'selected': selectedWarehouse && selectedWarehouse['rowid'] === item['rowid'] }"
              @click="selectWarehouse(item)">
              <view class="warehouse-info">
                <!-- 仓库名称 -->
                <text class="warehouse-name">{{ item['name'] }}</text>
              </view>
              <!-- 仓库状态 -->
           
            </view>
          </view>
        </view>
        
        <!-- 底部确认按钮 -->
        <view class="drawer-footer">
          <button class="confirm-btn" @click="confirmSelection">
            <text class="confirm-text">确认选择</text>
          </button>
            <button class="home-btn" @click="goToHome">
            <text class="home-icon">🏠</text>
            <text class="home-text">回到首页</text>
          </button>
        </view>
      </scroll-view>
    </view>
  </uni-drawer>
</template>

<script setup>
import { ref, watch, onMounted, computed } from 'vue'
import UniDrawer from '@dcloudio/uni-ui/lib/uni-drawer/uni-drawer.vue'
import http from '../utils/request'
import { useUserStore } from '../store/user'
import { useDrawerStore } from '../store/drawer'

// 使用 Pinia
const drawerStore = useDrawerStore()
const visible = computed(() => drawerStore.isVisible)
const showAddWarehouse = computed(() => drawerStore.showAddWarehouse)

// 新增输入框数据
const warehouseCode = ref('')

// 引入用户状态管理
const userStore = useUserStore()

// 定义组件props
const props = defineProps({
  // 抽屉宽度
  width: {
    type: [Number, String],
    default: 320
  },
  // 是否允许点击遮罩关闭
  maskClick: {
    type: Boolean,
    default: true
  },
  // 导航栏高度
  navHeight: {
    type: Number,
    default: 0
  }
})

// 定义事件
const emit = defineEmits(['update:modelValue', 'change', 'confirm'])

// 抽屉引用
const drawerRef = ref(null)

// 仓库列表数据
const warehouseList = ref([])

// 选中的仓库
const selectedWarehouse = ref(null)

// 刷新状态
const isRefreshing = ref(false)

// 加载更多状态
const isLoadingMore = ref(false)

// 监听store状态变化
watch(visible, (newVal) => {
  console.log('Drawer visibility changed:', newVal)
  if (newVal) {
    open()
  } else {
    close()
  }
})

// 打开抽屉
const open = () => {
  if (drawerRef.value) {
    drawerRef.value.open()
    // 打开时恢复选中的仓库
    restoreSelectedWarehouse()
  }
}

// 关闭抽屉
const close = () => {
  if (drawerRef.value) {
    drawerRef.value.close()
  }
  emit('update:modelValue', false)
  // 同步更新store状态
  drawerStore.closeDrawer()
}

// 处理抽屉状态变化
const handleChange = (e) => {
  emit('change', e)
  if (!e) {
    emit('update:modelValue', false)
    // 同步更新store状态
    drawerStore.closeDrawer()
  }
}

// 获取状态对应的CSS类名
const getStatusClass = (status) => {
  const statusMap = {
    '运行中': 'status-running',
    '待机中': 'status-standby',
    '维护中': 'status-maintenance',
    '启用': 'status-enabled',
    '禁用': 'status-disabled'
  }
  return statusMap[status] || ''
}

// 选择仓库
const selectWarehouse = (warehouse) => {
  selectedWarehouse.value = warehouse
  console.log('选择仓库:', warehouse)
}

// 恢复之前选择的仓库
const restoreSelectedWarehouse = () => {
  const currentWarehouseCode = userStore.getWarehouseCode()
  console.log('恢复选中的仓库代码:', currentWarehouseCode)
  
  if (currentWarehouseCode && warehouseList.value.length > 0) {
    const warehouse = warehouseList.value.find(item => item.rowid === currentWarehouseCode)
    if (warehouse) {
      selectedWarehouse.value = warehouse
      console.log('恢复选中的仓库:', warehouse)
    }
  }
}

// 确认选择
const confirmSelection = async () => {
  if (selectedWarehouse.value) {

  const res = await http.post('https://www.dachen.vip/api/workflow/hooks/NjhkNTM5NjI2M2RiN2Y4ZDhiMGY0NDE2', {
      userRowid: userStore.getUserInfo().rowid,
      warehouseCode: selectedWarehouse.value['rowid']
    })
    const res1 = userStore.getUserInfo()
    res1['68d5efc3b02e7bd374f192a3'] = selectedWarehouse.value['rowid']
    userStore.setUserInfo(res1)
    userStore.setWarehouseCode(selectedWarehouse.value['rowid'])
     uni.setStorageSync('cdx_merchant_userInfo', res1)
     console.log('本地存储数据', uni.getStorageSync('cdx_merchant_userInfo'));
     
    

    if(res){
    const url = '/pages/tabs/warehouse/warehouse?code=' + encodeURIComponent(selectedWarehouse.value['rowid'])
        uni.reLaunch({
          url
      })
    }
    close()
  } else {
    uni.showToast({
      title: '请先选择一个仓库',
      icon: 'none'
    })
  }
}

// 添加协同仓
const addWarehouse = async () => {
  
  if (!warehouseCode.value || warehouseCode.value.trim() === '') {
    uni.showToast({
      title: '请输入协同仓编码',
      icon: 'none'
    })
    return
  }

  console.log('传入数据', {  
      userRowid: userStore.getUserInfo().rowid,
      warehouseCode: warehouseCode.value
    });
  // 跳转到添加协同仓页面
 const res = await http.post('https://www.dachen.vip/api/workflow/hooks/NjhkNzNhYTcyMGQwZDY0YzAyZmZiOTc2', {  
      userRowid: userStore.getUserInfo().rowid,
      warehouseCode: warehouseCode.value
    }, {
      timeout: 30000
    })
    console.log('添加协同仓', res);
    if (res) {
      uni.showToast({
        title: '审批中',
        icon: 'success',
        duration: 2000
      })

      getStoreList()

    }
    else{
      uni.showToast({
        title: '未查询到该协同仓',
        icon: 'none',
        duration: 2000
      })
    }

    warehouseCode.value = ''
    
}

// 获取协同仓
const getStoreList = async () => {
  console.log('userStore.getUserInfo().rowid', userStore.getUserInfo().rowid);
  
  try {
    // 增加超时时间到30秒，避免网络慢导致超时
    const res = await http.post('https://www.dachen.vip/api/workflow/hooks/NjhjM2IzZDZlN2Q5ZjkwYmMwZWFiNWVk', {
      userRowid: userStore.getUserInfo().rowid
    }, {
      timeout: 30000
    })
    console.log('获取协同仓', JSON.parse(res.data));
    
    if (res) {
      warehouseList.value = JSON.parse(res.data).map(item => ({
        name: item["68ed0e356535f4c5482334ce"],
        rowid: item['68ed0da96535f4c5482334c4']
      }));
      
      // 恢复之前选择的仓库
      restoreSelectedWarehouse()
    }
  } catch (error) {
    console.error('获取协同仓失败:', error)
  }
}

// 处理下拉刷新
const handleRefresh = async () => {
  console.log('开始下拉刷新')
  isRefreshing.value = true
  
  try {
    // 调用获取数据的方法
    await getStoreList()
 
  } catch (error) {
    console.error('刷新失败:', error)
  } finally {
    // 延迟一点结束刷新状态，让用户能看到刷新效果
    setTimeout(() => {
      isRefreshing.value = false
    }, 500)
  }
}

// 处理加载更多（滚动到底部）
const handleLoadMore = () => {
  console.log('滚动到底部，触发加载更多')
  // 目前数据量不大，可以在这里添加分页逻辑
  // 暂时只做提示
  if (warehouseList.value.length > 0) {
    uni.showToast({
      title: '已加载全部数据',
      icon: 'none',
      duration: 1500
    })
  }
}

// 回到首页
const goToHome = () => {
  uni.reLaunch({
    url: '/pages/tabs/index'
  })
  close()
}

// 页面加载时执行
onMounted(() => {
  getStoreList()
})

// 暴露方法给父组件
defineExpose({
  open,
  close
})
</script>

<style lang="scss" scoped>
// 定义变量
$white: #FFFFFF;
$gray-100: #F8F9FA;
$gray-200: #E9ECEF;
$gray-300: #F0F0F0;
$gray-400: #F5F5F5;
$gray-500: #666666;
$gray-600: #333333;
$button-gradient: linear-gradient(45deg, #FF6B9B, #C44569);
$success-bg: #D4EDDA;
$success-text: #155724;
$warning-bg: #FFF3CD;
$warning-text: #856404;
$danger-bg: #F8D7DA;
$danger-text: #721C24;

.drawer-content {
  width: 100%;
  height: 100%;
  background: $white;
  display: flex;
  flex-direction: column;
}

.scroll-view-box {
  flex: 1;
  position: absolute;
  right: 0;
  bottom: 0;
  left: 0;
}

// 抽屉头部
.drawer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 40rpx 30rpx 20rpx;
  border-bottom: 2rpx solid $gray-300;
  background: $white;
}

.home-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(45deg, #FF9800, #F57C00);
  border: none;
  border-radius: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 12rpx rgba(255, 152, 0, 0.3);
  color: $white;
  font-size: 32rpx;
  font-weight: bold;
  transition: all 0.3s ease;
  margin-top: 20rpx;

  &:active {
    transform: scale(0.98);
    box-shadow: 0 2rpx 8rpx rgba(255, 152, 0, 0.4);
  }

  .home-icon {
    font-size: 36rpx;
    margin-right: 12rpx;
    font-weight: bold;
  }

  .home-text {
    font-size: 32rpx;
  }
}

.header-text {
  font-size: 36rpx;
  font-weight: bold;
  color: $gray-600;
}

.close-btn {
  width: 60rpx;
  height: 60rpx;
  background: $gray-400;
  border: none;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0;
}

.close-text {
  font-size: 40rpx;
  color: $gray-500;
  font-weight: bold;
  line-height: 1;
}

// 仓库列表
.warehouse-list {
  padding: 20rpx 30rpx;
}

.warehouse-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 20rpx;
  margin-bottom: 20rpx;
  background: $gray-100;
  border-radius: 16rpx;
  border: 2rpx solid transparent;

  &:active {
    background: $gray-200;
    border-color: #FF6B9B;
  }

  &.selected {
    background: #FF6B9B;
    border-color: #FF6B9B;
    box-shadow: 0 4rpx 12rpx rgba(255, 107, 155, 0.3);
    
    .warehouse-name {
      color: $white;
    }
    
    .warehouse-desc {
      color: rgba(255, 255, 255, 0.8);
    }
    
    .warehouse-status {
      background: rgba(255, 255, 255, 0.2);
      
      .status-text {
        color: $white;
      }
    }
  }
}

.warehouse-info {
  flex: 1;
}

.warehouse-name {
  display: block;
  font-size: 32rpx;
  font-weight: bold;
  color: $gray-600;
  margin-bottom: 8rpx;
}

.warehouse-desc {
  display: block;
  font-size: 24rpx;
  color: $gray-500;
  line-height: 1.4;
}

// 仓库状态
.warehouse-status {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  margin-left: 20rpx;

  &.status-running {
    background: $success-bg;
    
    .status-text {
      color: $success-text;
    }
  }

  &.status-standby {
    background: $warning-bg;
    
    .status-text {
      color: $warning-text;
    }
  }

  &.status-maintenance {
    background: $danger-bg;
    
    .status-text {
      color: $danger-text;
    }
  }
  
  &.status-enabled {
    background: $success-bg;
    
    .status-text {
      color: $success-text;
    }
  }
  
  &.status-disabled {
    background: $danger-bg;
    
    .status-text {
      color: $danger-text;
    }
  }
}

.status-text {
  font-size: 22rpx;
  font-weight: bold;
}

// 空状态样式
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 40rpx;
  text-align: center;
}

.empty-icon {
  font-size: 80rpx;
  margin-bottom: 30rpx;
  opacity: 0.5;
}

.empty-title {
  font-size: 32rpx;
  color: $gray-600;
  font-weight: bold;
  margin-bottom: 16rpx;
}

.empty-desc {
  font-size: 28rpx;
  color: $gray-500;
  line-height: 1.5;
}

// 抽屉底部
.drawer-footer {
  padding: 30rpx;
  border-top: 2rpx solid $gray-300;
  background: $white;
}

// 刷新提示样式
.refresh-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx;
  background: rgba(76, 175, 80, 0.1);
  border-radius: 16rpx;
  margin-bottom: 20rpx;
}

.refresh-icon {
  font-size: 32rpx;
  margin-right: 12rpx;
  animation: rotate 1s linear infinite;
}

.refresh-text {
  font-size: 28rpx;
  color: #4CAF50;
  font-weight: 500;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.confirm-btn {
  width: 100%;
  height: 88rpx;
  background: $button-gradient;
  border: none;
  border-radius: 44rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 4rpx 12rpx rgba(255, 107, 155, 0.3);
  color: $white;
  font-size: 32rpx;
  font-weight: bold;
}

// 添加协同仓区域样式
.add-warehouse-section {
  padding: 20rpx 30rpx;
  border-bottom: 2rpx solid $gray-300;
}

.input-wrapper {
  position: relative;
  margin-bottom: 20rpx;
}

.warehouse-input {
  width: 100%;
  height: 88rpx;
  padding: 0 80rpx 0 30rpx;
  font-size: 32rpx;
  color: $gray-600;
  background: $gray-100;
  border: 2rpx solid $gray-300;
  border-radius: 44rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;

  &:focus {
    background: $white;
    border-color: #FF6B9B;
    box-shadow: 0 4rpx 16rpx rgba(255, 107, 155, 0.15);
    outline: none;
  }

  &::placeholder {
    color: $gray-500;
    font-size: 28rpx;
  }
}

.input-icon {
  position: absolute;
  right: 30rpx;
  top: 50%;
  transform: translateY(-50%);
  font-size: 32rpx;
  color: $gray-500;
  pointer-events: none;
}

.add-warehouse-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(45deg, #4CAF50, #45a049);
  border: none;
  border-radius: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 12rpx rgba(76, 175, 80, 0.3);
  color: $white;
  font-size: 32rpx;
  font-weight: bold;
  transition: all 0.3s ease;

  &:active {
    transform: scale(0.98);
    box-shadow: 0 2rpx 8rpx rgba(76, 175, 80, 0.4);
  }

  .add-icon {
    font-size: 36rpx;
    margin-right: 12rpx;
    font-weight: bold;
  }

  .add-text {
    font-size: 32rpx;
  }
}
</style>